/**
 * 职级选择器
 */
import React from 'react';
import { TreeSelect, Spin } from 'antd';
import { getGradeList } from '@/services/organization';
import { useRequest, defaultFormatResult } from '@/hooks';
import styles from './Grade.less';

const { TreeNode } = TreeSelect;

const renderTreeNodes = (tree, fieldsName) =>
    tree.map(item => (
        <TreeNode value={item[fieldsName.value]} title={item[fieldsName.title]} key={item[fieldsName.value]}>
            {item.children ? renderTreeNodes(item.children, fieldsName) : null}
        </TreeNode>
    ));

const Grade = React.forwardRef(
    ({ value, onChange, fieldsName = { value: 'rankValue', title: 'rankValue' }, ...rest }, ref) => {
        const { data: gradeList, loading } = useRequest(getGradeList, {
            ...defaultFormatResult
        });

        return (
            <Spin spinning={loading}>
                <TreeSelect
                    multiple
                    ref={ref}
                    dropdownClassName={styles.treeSelectDropDown}
                    treeCheckable
                    dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                    placeholder="请选择或输入"
                    allowClear
                    maxTagCount={1}
                    style={{ width: '100%' }}
                    treeNodeFilterProp="title"
                    getPopupContainer={trigger => trigger.parentNode}
                    onChange={onChange}
                    value={value}
                    {...rest}
                >
                    {renderTreeNodes(gradeList || [], fieldsName)}
                </TreeSelect>
            </Spin>
        );
    }
);

export default Grade;
